﻿using Baidu.Push.Api.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace PushConsole
{
    [ServiceContract]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class PushService
    {
        public const string TAG = "host";
        protected Dictionary<string, QueryBindItem> users = new Dictionary<string, QueryBindItem>();

        public PushService()
        {
            PushHelper.DeleteTag(TAG);
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        [OperationContract]
        [WebInvoke(UriTemplate = "Login/{user_id}", Method = "GET")]
        public void Login(string user_id)
        {
            var user = PushHelper.GetBindList(user_id).FirstOrDefault();
            if (user != null && !users.ContainsKey(user_id))
            {
                PushHelper.SetTag(TAG, user_id);
                users[user_id] = user;
            }
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
        }

        /// <summary>
        /// 获取在线用户列表
        /// </summary>
        [OperationContract]
        [WebInvoke(UriTemplate = "UserListGet", Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        public IEnumerable<string> UserListGet()
        {
            return users.Values.Select(t => t.DeviceName).ToArray();
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        [OperationContract]
        [WebInvoke(UriTemplate = "SendNotification/{desc}", Method = "GET")]
        public void SendNotification(string desc)
        {
            var msg = new PushMessage(desc);
            PushHelper.PushClient.PushNotificationByTag(DeviceType.Andriod, msg, TAG);
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
        }

        /// <summary>
        /// 用户登出
        /// </summary>
        [OperationContract]
        [WebInvoke(UriTemplate = "LogOut/{user_id}", Method = "GET")]
        public void LogOut(string user_id)
        {
            if (users.ContainsKey(user_id))
            {
                PushHelper.DeleteTag(TAG, user_id);
                users.Remove(user_id);
            }
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
        }
    }
}
